<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/21
 * Time: 16:58
 */

namespace Multiple\Home\Controllers;

use Asa\Erp\TbPicture;

class TestController extends AdminController
{


    public function initialize()
    {
        parent::initialize();

        $this->setModelName('Asa\\Erp\\TbPicture');
    }

    public function pageAction(){
        $num = $this->session->get('num');
        if(!$num){
            $num = 2;
        }
        $products = TbPicture::find(
            sprintf("productid<=%d and productid>=%d",($num-1)*5,($num-2)*5)
        );
        $path = 'http://pic.e-asa.com/';
        $list = $products->toArray();

        foreach($list as $k=>$v){
            $file_name = $this->download($path.$v['filename'],'./public/upload/product/',$v['filename']);
        }
        $this->session->set('num',$num+1);
    }

    function download($url, $save_dir,$filename='')
    {
        if(trim($save_dir)=='')
            $save_dir='./';

        if(trim($filename)==''){//保存文件名
            $allowExt = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
            $ext=strrchr($url,'.');
            if(!in_array($ext,$allowExt))
                return array('file_name'=>'','save_path'=>'','error'=>3);

            $filename=time().$ext;
        }

        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true))
            return array('file_name'=>'','save_path'=>'','error'=>5);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($save_dir . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        unset($file,$url);
        return json_encode(array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>'无错误，上传成功！'));
    }


}